package com.zyjc.city.util;

import java.util.HashSet;

/**
 * @author ckj
 * @date 2024年04月01日 17:06
 */
public class SnowflakeId {
    private static final long START_STMP = 1624259101684L;
    private static final long SEQUENCE_BIT = 12L;
    private static final long MACHINE_BIT = 5L;
    private static final long DATACENTER_BIT = 5L;
    private static final long MAX_DATACENTER_NUM = 31L;
    private static final long MAX_MACHINE_NUM = 31L;
    private static final long MAX_SEQUENCE = 4095L;
    private static final long MACHINE_LEFT = 12L;
    private static final long DATACENTER_LEFT = 17L;
    private static final long TIMESTMP_LEFT = 22L;
    private long datacenterId;
    private long machineId;
    private long sequence = 0L;
    private long lastStmp = -1L;

    private final static SnowflakeId INSTANCE = new SnowflakeId(1,2);

    public static SnowflakeId getInstance() {
        return INSTANCE;
    }

    private SnowflakeId(long dataCenterId, long machineId) {
        if (dataCenterId <= 31L && dataCenterId >= 0L) {
            if (machineId <= 31L && machineId >= 0L) {
                this.datacenterId = dataCenterId;
                this.machineId = machineId;
            } else {
                throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
            }
        } else {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
    }

    public synchronized long nextId() {
        long currStmp = this.timeGen();
        if (currStmp < this.lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        } else {
            if (currStmp == this.lastStmp) {
                this.sequence = this.sequence + 1L & 4095L;
                if (this.sequence == 0L) {
                    currStmp = this.getNextMill();
                }
            } else {
                this.sequence = 0L;
            }

            this.lastStmp = currStmp;
            return currStmp - 1624259101684L << 22 | this.datacenterId << 17 | this.machineId << 12 | this.sequence;
        }
    }

    public static long getId(){
       return INSTANCE.nextId();
    }

    private long getNextMill() {
        long mill;
        for(mill = this.timeGen(); mill <= this.lastStmp; mill = this.timeGen()) {
        }

        return mill;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        HashSet<Long> set=new HashSet();
        for (int i = 0; i <2 ; i++) {
            set.add(INSTANCE.nextId());
        }
        System.out.println(set);
    }
}
